/* 
 * File:   Http.h
 * Author: tzl
 *
 * Created on July 1, 2011, 11:45 AM
 */

#ifndef HTTP_H
#define	HTTP_H

#define HTTP_CRLF				"\r\n"

class HttpReqBuilder {
public:
	~HttpReqBuilder();
	bool setReqInfo(const std::string& reqType, const std::string& host,
		const std::string& uri);
	bool addHeader(const std::string& hdrname, const std::string& hdrvalue);
	bool setData(const char* databuf, size_t len);

	// now it's utfi-8
	bool setEncodeFormat(const std::string& encode) { return false; }
	bool buildPacket(char* outbuf, size_t len);
	std::string buildPacket();

protected:
	inline size_t computePacketSize() const;

protected:
	std::string		_reqType;
	std::string		_host;
	std::string		_uri;
	typedef std::vector<std::pair<std::string, std::string> > Headers;
	Headers			_headers;
	char*			_data;
	size_t			_datalen;
};

////////////////////////////////////////////////////////////////////////////

#define MAX_HTTP_RESP			4096
#define HTTP_CONTENT_LENGTH		"Content-Length"
#define HTTP_TRANSFER_ENCODING_CHUNK  "Transfer-Encoding: chunked"

class HttpResponseParser {
public:
	HttpResponseParser(size_t len = MAX_HTTP_RESP);
	~HttpResponseParser();
	bool parse(const char* buf, size_t len);
	size_t getResponseSize() const;
	size_t getResponse(char* buf, size_t buflen, size_t* datapos);

protected:
	char*		_buf;
	size_t		_len;
	size_t		_pos;

	enum RespState {
		NeedHeader,
		NeedData,
		RespOK,
	};

	RespState	_state;
	size_t		_hdrLen;
	size_t		_dataLen;
};

#endif	/* HTTP_H */
